<script setup>
	import {
		ref
	} from "vue";
	import {
		onLoad,
		onShareAppMessage
	} from '@dcloudio/uni-app'

	const roomManage = uniCloud.importObject('room-manage')

	const navbarOptions = {}

	const roomCode = ref('')
	const roomUsers = ref([])
	const userInfoData = ref({})

	const menuButton = ref(uni.getMenuButtonBoundingClientRect())
	const pageHeight = ref(`calc(100vh - ${menuButton.value.top+menuButton.value.height}px - 80rpx)`)

	const openid = ref(getApp().globalData.openid)

	onLoad(async (option) => {
		uni.showLoading({
			title: '嘿嘿嘿~',
			mask: true
		})
		if (!option.roomCode) {
			await createRoom()
			uni.hideLoading()
		} else {
			await joinRoom(option.roomCode)
			uni.hideLoading()
			getQueryParams()
		}
	})

	function getQueryParams() {
		var options = wx.getLaunchOptionsSync().query;
		console.log('Scan query:', options);

		// 如果你想根据参数做某些事情
		if (options.scene) {
			// 这里可以处理 scene 参数
			console.log('Scene ID:', options.scene);
			createRoom(options.scene)
		}

		if (options.key) {
			// 处理其他参数
			console.log('Key:', options.key);
		}
	}

	// 创建房间
	async function createRoom() {
		const {
			RetObject,
			RetMessage,
			RetCode
		} = await roomManage.creatRoom(openid.value)
		if (RetCode === 0) {
			roomCode.value = RetObject.roomCode
			roomUsers.value = RetObject.users
			userInfoData.value = RetObject.users.find(item => item.userID === openid.value)
		} else {
			uni.showToast({
				title: '创建失败!请联系开发者!',
				icon: 'error'
			})
		}
	}

	// 加入房间
	async function joinRoom(rCode) {
		const {
			RetObject,
			RetMessage,
			RetCode
		} = await roomManage.joinRoom(openid.value, rCode)
		if (RetCode === 0) {
			roomCode.value = RetObject.roomCode
			roomUsers.value = RetObject.users
			userInfoData.value = RetObject.users.find(item => item.userID === openid.value)
		} else {
			uni.showToast({
				title: '加入失败!',
				icon: 'error'
			})
		}
	}

	// 跳转到个人中心
	function toPersonalCenter() {
		uni.navigateTo({
			url: '../personalCenter/index',
			animationType: 'pop-in',
			animationDuration: 200
		})
	}


	const appId = 'wx2ee954f54dc71599';
	const appSecret = 'ba6aa60ef7f7c5b1e7dc3ad8b1507b6c';
	const pagePath = '/pages/room/index'; // 小程序页面路径

	const qrCodeBase64 = ref(uni.getStorageSync('qrCodeBase64'))
	const qrCodePopup = ref(null)

	// 邀请好友加入房间
	async function inviteFriends() {
		uni.showLoading({
			title: '客观，稍等！',
			mask: true
		})
		const qrBase64 = uni.getStorageSync('qrCodeBase64')
		if (qrBase64) {
			uni.hideLoading()
			return qrCodePopup.value.open('center')
		}
		getAccessToken((access_token) => {
			generateMiniProgramCode(access_token, roomCode.value || 'testRoomCode', pagePath);
		});
	}

	// 获取 access_token
	function getAccessToken(callback) {
		const url =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
		uni.request({
			url,
			success: ({
				data
			}) => {
				if (!data.errcode) {
					callback(data.access_token)
				} else {
					uni.showToast({
						title: '生成二维码失败!',
						icon: 'error',
					})
				}
			}
		})
	}

	// 生成小程序码
	function generateMiniProgramCode(access_token, scene, page) {
		const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`;
		uni.request({
			method: 'POST',
			url,
			responseType: 'arraybuffer', // 注意一定要加 不然返回的Buffer流会乱码 导致无法转base64
			data: {
				scene,
			},
			success: ({
				data
			}) => {
				if (!data.errcode) {
					const base64 = 'data:image/png;base64,' + uni.arrayBufferToBase64(data)
					// 显示二维码
					qrCodeBase64.value = base64
					uni.setStorageSync('qrCodeBase64', base64);
					qrCodePopup.value.open('center')
				} else {
					uni.showToast({
						title: '生成二维码失败!',
						icon: 'error',
					})
				}
				uni.hideLoading()
			},
		})
	}

	// 关闭分享
	function closeQrCodePopup() {
		qrCodePopup.value.close()
	}

	// 离开房间
	async function leaveRoom() {
		const {
			RetObject,
			RetMessage,
			RetCode
		} = await roomManage.leaveRoom(openid.value, roomCode.value)
		if (RetCode === 0) {
			uni.setStorageSync('qrCodeBase64', '');
			const openPageNums = getCurrentPages().length
			if (openPageNums === 1) {
				uni.reLaunch({
					url: '../home/index'
				});
			} else {
				uni.navigateBack({
					delta: 1
				});
			}
		} else {
			uni.showToast({
				title: '离开失败，请不要离开!',
				icon: 'error'
			})
		}
	}

	// 转账弹窗ref
	const transferPop = ref(null)
	//转账数
	const transferNumber = ref('')

	const receiveUser = ref({})

	// 开启转账键盘
	function transferMoney(data) {
		// if (openid.value === data.userID) return
		receiveUser.value = data
		transferPop.value.open()
	}
	// 关闭转账键盘
	function closeTransferPop() {
		receiveUser.value = {}
		transferPop.value.close()
	}

	// 键盘列表
	const keyboardList = ref([{
			value: 0,
			label: 0,
			isActive: false,
		},
		{
			value: 1,
			label: 1,
			isActive: false,
		},
		{
			value: 2,
			label: 2,
			isActive: false,
		},
		{
			value: 3,
			label: 3,
			isActive: false,
		},
		{
			value: 4,
			label: 4,
			isActive: false,
		},
		{
			value: 5,
			label: 5,
			isActive: false,
		},
		{
			value: 6,
			label: 6,
			isActive: false,
		},
		{
			value: 7,
			label: 7,
			isActive: false,
		},
		{
			value: 8,
			label: 8,
			isActive: false,
		},
		{
			value: 9,
			label: 9,
			isActive: false,
		},
		{
			value: '确认',
			label: 'ok',
			isActive: false,
		},
		{
			value: '.',
			label: 'point',
			isActive: false,
		},
		{
			value: '',
			label: 'del',
			isActive: false,
		},
	])

	// 键盘按下
	function keyboardDown(key) {
		key.isActive = true
	}

	// 键盘抬起
	function keyboardUp(key) {
		uni.vibrateShort();
		key.isActive = false
		switch (key.label) {
			case 'ok':
				confirmTransfer()
				break
			case 'del':
				transferNumber.value = transferNumber.value.slice(0, -1)
				break
			default:
				handleKeyboard(key.value)
		}
	}

	function handleKeyboard(value) {
		const initVal = transferNumber.value
		if (value === '.' && (initVal === '' || initVal === '0')) {
			return transferNumber.value = '0.'
		}
		const reg = /^(?:0|[1-9]\d{0,4})(?:\.\d{0,2})?$/
		const newVal = (initVal === '0' ? '' : initVal) + value
		if (reg.test(newVal)) {
			transferNumber.value = newVal
		}
	}

	function confirmTransfer() {
		console.log('确认!')
		if (transferNumber.value === '' || /^0(\.0*)?$/.test(transferNumber.value)) {
			uni.showToast({
				title: '请输入金额',
				icon: 'none',
				duration: 1000
			})
		} else {
			transferNumber.value = ''
			transferPop.value.close()
		}
	}

	function sendMessage() {
		// promise方式
		uniCloud.callFunction({
				name: 'user-id',
				data: {
					a: 1
				}
			})
			.then(res => {
				console.log(res, 'sendMessage')
			});
	}

	onShareAppMessage((res) => {
		console.log(res, '分享按钮点击');
		if (res.from === 'button') { // 来自页面内分享按钮
			console.log(res.target)
		}
		return {
			title: '朋友邀请你加入房间',
			imageUrl: '', // TODO: 制作一个分享图
			path: `/pages/room/index?roomCode=${roomCode.value}`
		}
	})
</script>

<template>
	<navbar v-bind="navbarOptions"></navbar>
	<uni-popup ref="qrCodePopup" type="center">
		<view class="qr-code-box">
			<view class="qr-code-close" @click="closeQrCodePopup"><uni-icons type="closeempty" size="22"></uni-icons></view>
			<view class="qr-code-title">邀请好友加入</view>
			<view class="qr-code-image">
				<image :src="qrCodeBase64" style="width: 360rpx;height: 360rpx;" show-menu-by-longpress></image>
			</view>
			<view class="qr-code-share">
				<button class="share-btn" type="default" open-type="share" :plain="true">发送给好友</button>
			</view>
		</view>
	</uni-popup>
	<view class="room-page" :style="{height:pageHeight}">
		<view class="user-info" @click="toPersonalCenter">
			<image class="image-circle" style="width: 120rpx;height: 120rpx;box-shadow: 4rpx 6rpx 2rpx rgba(0, 0, 0, 0.3);"
				:src="userInfoData.avatarURL"></image>
			<view class="nickname-wrapper">
				<view class="nickname-text">{{ userInfoData.name }}</view>
				<view class="welcome-text">欢迎使用，祝你玩的开心~</view>
			</view>
			<button class="personal-center">个人中心</button>
		</view>

		<view class="my-points">
			<view class="points-title">我的积分</view>
			<view class="points">
				<view class="points-number">{{ userInfoData.integral}}</view>
				<text class="iconfont icon-flush points-flush"></text>
			</view>
			<view class="points-rank">
				<view class="my-rank">我的排名: {{ 3 }}</view>
				<view class="points-detail"><text>积分明细</text><text class="iconfont icon-forward points-forward"></text></view>
			</view>
		</view>

		<view class="room-content">
			<view class="room-contain">
				<view class="">房间({{ roomUsers.length }}人)</view>
				<text class="iconfont icon-add add-new-user" @click="inviteFriends"></text>
			</view>
			<scroll-view scroll-y class="user-info-wrapper">
				<view class="user-info-single" v-for="item in roomUsers" :key="item.userID"
					:class="{'is-my-info': item.userID === openid}">
					<image class="image-circle user-head-image" :src="item.avatarURL"></image>
					<text class="user-name">{{ item.name }}</text>
					<text class="user-points">{{ item.integral}}分</text>
					<view :style="{opacity:(openid === item.userID)?0:1 }" class="transfer-btn" @click="transferMoney(item)">转账
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="btn-bottom">
			<view class="leave-room" @click="leaveRoom">离开房间</view>
			<view class="settlement-points" @click="sendMessage">结算积分</view>
		</view>


	</view>
	<uni-popup ref="transferPop" type="bottom">
		<view class="transfer-pop">

			<view class="display-flex transfer-pop-top">
				<view class="close-icon-box" @click="closeTransferPop">
					<text class="iconfont icon-guanbi close-icon"></text>
				</view>
				<view class="title">
					<text>转账</text>
				</view>
			</view>

			<view style="margin-top: 40rpx;" class="display-flex">
				<view class="user-info">
					<image class="image-circle head-image" :src="userInfoData.avatarURL"></image>
					<text style="padding-top: 4rpx;">userInfoData.name</text>
				</view>
				<view class="middle-box">
					<text style="margin-bottom: 10rpx;font-size: 32rpx; font-weight: bold;">转给</text>
					<text style="font-size: 40rpx;" class="iconfont icon-youjiantou"></text>
				</view>
				<view class="user-info">
					<image class="image-circle head-image" :src="receiveUser.avatarURL"></image>
					<text style="padding-top: 4rpx;">receiveUser.name</text>
				</view>
			</view>

			<view class="transfer-amount">
				<view v-if="transferNumber === ''" class="analog-cursor"></view>
				<text v-else>{{ transferNumber }}</text>
			</view>

			<view class="keyboard-number">
				<view class="angry-grid">
					<view v-for="(item,index) in keyboardList" :key="index" :id="`item-${item.label}`"
						:class="['keyboard-key',item.isActive?'keyboard-active':'']" @touchstart="keyboardDown(item)"
						@touchend="keyboardUp(item)">
						<text :class="[item.label === 'del'?'iconfont icon-chehui':'']">{{ item.value }}</text>
					</view>
				</view>
			</view>

		</view>
	</uni-popup>
</template>

<style lang="scss">
	.qr-code-box {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 500rpx;
		padding: 20rpx 60rpx;
		border-radius: 20rpx;
		background-color: #ffffff;

		.qr-code-close {
			position: absolute;
			top: 36rpx;
			right: 24rpx;
		}

		.qr-code-title {
			font-size: 32rpx;
			padding: 20rpx;
		}

		.qr-code-image {
			margin: 10rpx 0;
		}

		.qr-code-share {
			width: 100%;
			margin: 30rpx 0 20rpx;
			background-color: #000;

			.share-btn {
				color: #ffffff;
				border-radius: 6rpx;
				font-size: 28rpx;
			}
		}
	}

	.room-page {
		position: relative;
		padding: 40rpx;
		display: flex;
		flex-direction: column;

		.user-info {
			display: flex;
			align-items: center;

			.nickname-wrapper {
				padding-left: 16rpx;

				&>view {
					padding: 4rpx 0;
				}

				.nickname-text {
					width: 360rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					font-weight: bold;
				}

				.welcome-text {
					font-size: 24rpx;
					font-weight: 200;
				}
			}

			.personal-center {
				margin: 0 0 0 auto;
				padding: 0 10rpx;
				height: 50rpx;
				line-height: 50rpx;
				border: 2rpx solid var(--theme-color);
				border-radius: 50rpx;
				font-size: 24rpx;
				color: var(--theme-color);
				background-color: transparent;
			}
		}

		.my-points {
			padding: 0 25rpx;
			margin: 30rpx 0;
			border-radius: 20rpx;
			background-image: linear-gradient(to bottom, rgba(98, 101, 242, 1), rgba(98, 101, 242, .7));
			color: #ffffff;
			font-weight: 100;

			.points-title {
				padding: 25rpx 0;
			}

			.points {
				display: flex;
				justify-content: space-between;
				height: 150rpx;

				.points-number {
					font-size: 40rpx;
					font-weight: 600;
				}

				.points-flush {
					&:before {
						padding: 10rpx;
						border-radius: 50%;
						background-color: rgba(255, 255, 255, .3);
						font-size: 40rpx;
					}
				}
			}

			.points-rank {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
				font-size: 24rpx;

				.points-forward {
					padding-left: 6rpx;
					font-size: 20rpx;
				}
			}
		}

		.room-content {
			flex: 1;
			overflow: hidden;

			.room-contain {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-weight: 700;

				.add-new-user {
					font-size: 36rpx;
					color: var(--theme-color);
				}
			}

			.user-info-wrapper {
				padding: 20rpx 0;
				max-height: 710rpx;

				.user-info-single {
					box-sizing: border-box;
					display: flex;
					align-items: center;
					padding: 20rpx;
					margin: 20rpx 0;
					border-radius: 8rpx;
					background-color: #ffffff;

					.user-head-image {
						width: 90rpx;
						height: 90rpx;
						box-shadow: 2rpx 5rpx 2rpx rgba(0, 0, 0, 0.3);
					}

					.user-name {
						margin-left: 15rpx;
						font-weight: 500;
						white-space: nowrap;
						max-width: 240rpx;
						overflow: hidden;
						text-overflow: ellipsis;

					}

					.user-points {
						margin-left: auto;
						margin-right: 60rpx;
						font-weight: 900;
					}

					.transfer-btn {
						padding: 18rpx 25rpx;
						border-radius: 4rpx;
						color: var(--theme-color);
						font-size: 24rpx;
						font-weight: 500;
						background-color: rgba(98, 101, 242, .1);
						box-shadow: 2rpx 4rpx 4rpx rgba(0, 0, 0, .2);

						&:active {
							background-color: rgba(98, 101, 242, .2);
							box-shadow: none;
						}
					}
				}

				.is-my-info {
					border: 2rpx solid var(--theme-color);
					border-left: 8rpx solid var(--theme-color);
					border-right: 8rpx solid var(--theme-color);
					padding: 20rpx 12rpx;
				}
			}
		}

		.btn-bottom {
			display: flex;
			align-items: center;
			justify-content: space-between;
			color: #ffffff;

			.leave-room,
			.settlement-points {
				width: 48%;
				padding: 35rpx 0;
				margin: 40rpx 0 60rpx 0;
				border-radius: 6rpx;
				text-align: center;
			}

			.leave-room {
				background-color: #010101;

				&:active {
					background-color: rgba(1, 1, 1, .8);
				}
			}

			.settlement-points {
				background-color: var(--theme-color);

				&:active {
					background-color: rgba(98, 101, 242, .8);
				}
			}
		}
	}


	.transfer-pop {
		background-color: #ffffff;
		height: 50vh;
		padding: 40rpx 30rpx 0;
		border-radius: 20rpx 20rpx 0 0;

		.transfer-pop-top {
			.close-icon-box {
				width: 30rpx;
				height: 30rpx;

				.close-icon {
					font-size: 30rpx;
				}
			}

			.title {
				flex-grow: 1;
				padding-right: 30rpx;
				text-align: center;
				font-size: 24rpx;
			}
		}

		.user-info {
			flex-basis: 45%;
			display: flex;
			flex-direction: column;
			align-items: center;

			&>image {
				width: 100rpx;
				height: 100rpx;
			}

			&>text {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				font-size: 24rpx;
			}
		}

		.middle-box {
			flex: 1;
			padding-top: 30rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}

		.transfer-amount {
			position: relative;
			width: 100%;
			height: 60rpx;
			padding: 20rpx 0;
			margin: 40rpx 0;
			background-color: rgb(98, 101, 242, 0.3);
			text-align: center;
			line-height: 60rpx;
			border-radius: 10rpx;
			font-size: 56rpx;

			.analog-cursor {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				height: 40rpx;
				width: 2rpx;
				background-color: #010101;
				animation: blink 1s linear infinite;
			}

			@keyframes blink {
				0% {
					opacity: 1;
				}

				50% {
					opacity: 0;
				}

				100% {
					opacity: 1;
				}
			}
		}


		.keyboard-number {
			height: 50%;
			padding: 6rpx;
			background-color: rgb(98, 101, 242, 0.3);
			border-radius: 8rpx;

			.angry-grid {
				display: grid;

				grid-template-rows: 1fr 1fr 1fr 1fr;
				grid-template-columns: 1fr 1fr 1fr 1fr;

				gap: 0px;
				height: 100%;
			}

			.keyboard-key {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 6rpx;
				border-radius: 10rpx;
				background-color: #ffffff;
			}

			.keyboard-active {
				background-color: rgba(255, 255, 255, 0.3);
			}

			#item-0 {
				grid-row-start: 4;
				grid-column-start: 1;

				grid-row-end: 5;
				grid-column-end: 3;
			}

			#item-1 {
				grid-row-start: 1;
				grid-column-start: 1;

				grid-row-end: 2;
				grid-column-end: 2;
			}

			#item-2 {
				grid-row-start: 1;
				grid-column-start: 2;

				grid-row-end: 2;
				grid-column-end: 3;
			}

			#item-3 {
				grid-row-start: 1;
				grid-column-start: 3;

				grid-row-end: 2;
				grid-column-end: 4;
			}

			#item-4 {
				grid-row-start: 2;
				grid-column-start: 1;

				grid-row-end: 3;
				grid-column-end: 2;
			}

			#item-5 {
				grid-row-start: 2;
				grid-column-start: 2;

				grid-row-end: 3;
				grid-column-end: 3;
			}

			#item-6 {
				grid-row-start: 2;
				grid-column-start: 3;

				grid-row-end: 3;
				grid-column-end: 4;
			}

			#item-7 {
				grid-row-start: 3;
				grid-column-start: 1;

				grid-row-end: 4;
				grid-column-end: 2;
			}

			#item-8 {
				grid-row-start: 3;
				grid-column-start: 2;

				grid-row-end: 4;
				grid-column-end: 3;
			}

			#item-9 {
				grid-row-start: 3;
				grid-column-start: 3;

				grid-row-end: 4;
				grid-column-end: 4;
			}

			#item-ok {

				grid-row-start: 2;
				grid-column-start: 4;

				grid-row-end: 5;
				grid-column-end: 5;

				background-color: rgba(98, 101, 242, .5);
				color: #ffffff;
			}

			#item-point {
				grid-row-start: 4;
				grid-column-start: 3;

				grid-row-end: 5;
				grid-column-end: 4;
			}

			#item-del {
				grid-row-start: 1;
				grid-column-start: 4;

				grid-row-end: 2;
				grid-column-end: 5;

				color: red;
			}
		}

	}
</style>